package com.imooc.apigateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * 跨域配置
 * Cors 代表 C - Cross  O - Origin  R - Resource  S - Sharing
 * @author steve
 * @date 2020/6/28 15:34
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        //跨域配置
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); //支持cookie跨域
        config.setAllowedOrigins(Arrays.asList("*"));//原始域名 http://www.a.com
        config.setAllowedHeaders(Arrays.asList("*")); //允许所有头跨域
        config.setAllowedMethods(Arrays.asList("*")); //允许所有方法，比如GET,POST等
        config.setMaxAge(300L); //缓存时间，在这个时间段中，相同的跨域请求不在检查

        //跨域配置注册到source,路径是针对所有方法
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
